# -*- coding:utf-8 -*-
"""
@author:Mr.头发又黑又长
@file: bookserialization.py
@time: 2020/05/07
"""
import datetime

from rest_framework import serializers

from apps.user.util import MyAPIException
from common.response_code import RET, error_map
from db.models import XlzDisburse, XlzIncomeDisburseType, XlzIncome, XlzPlan


class DisburseIncomeSerialization(serializers.Serializer):
    """
    支出和收入模型反序列化序器
    """
    keepaccounts_type = serializers.CharField(required=True)
    user_id = serializers.IntegerField()
    type_id = serializers.IntegerField()
    money = serializers.FloatField()
    description = serializers.CharField(required=False)
    keepaccounts_time = serializers.DateTimeField(required=False)

    def validate_keepaccounts_type(self, value):
        if not value in ["disburse", "income"]:
            raise MyAPIException({"msg": error_map[RET.PARAMERR], 'code': RET.PARAMERR})
        return value

    def validate_type_id(self, value):
        try:
            XlzIncomeDisburseType.objects.get(pk=value)
            return value
        except Exception:
            raise MyAPIException({"msg": error_map[RET.TYPE_ID_ERROR], 'code': RET.TYPE_ID_ERROR})

    def validate_money(self, value):
        if value <= 0:
            raise MyAPIException({"msg": error_map[RET.MONEY_ERROR], 'code': RET.MONEY_ERROR})

        return value

    def create(self, validated_data):

        user_id = validated_data.get("user_id")
        type_id = validated_data.get("type_id")
        money = validated_data.get("money")
        description = validated_data.get("description", "")
        keepaccounts_time = validated_data.get("keepaccounts_time", datetime.datetime.now())

        if validated_data.get("keepaccounts_type") == "disburse":

            return XlzDisburse(user_id=user_id, type_id=type_id, money=money, description=description,
                               keepaccounts_time=keepaccounts_time)
        else:
            return XlzIncome(user_id=user_id, type_id=type_id, money=money, description=description,
                             keepaccounts_time=keepaccounts_time)


class IncomeDisburseTypeSerialization(serializers.ModelSerializer):
    class Meta:
        model = XlzIncomeDisburseType
        fields = ("id", "name", "img_url")


class PlanSerialization(serializers.ModelSerializer):
    class Meta:
        model = XlzPlan
        fields = ("id", "img_url", "target", "money", "is_activate")
